package com.pro.common.login.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pro.common.api.enums.EnumSysRole;
import com.pro.common.api.exception.BusinessException;
import com.pro.common.api.model.ILoginInfo;
import com.pro.common.api.model.request.ILoginRequest;
import com.pro.framework.api.util.AssertUtil;
import com.pro.framework.api.util.PasswordUtils;
import com.pro.framework.api.util.StrUtils;
import com.pro.framework.mybatisplus.BaseService;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Set;

public abstract class BaseLoginInfoService<M extends BaseMapper<T>, T extends ILoginInfo> extends BaseService<M, T> {

    public abstract T getLoginInfo(ILoginRequest loginRequest);
    public abstract EnumSysRole getSysRole();

    public Set<Long> getRoleIds(Long loginId) {
        return Set.of();
    }

    public void doAfterLogin(T loginInfo) {

    }

    /**
     * 更新不重要的信息
     *
     */
    public void update(ILoginInfo loginInfo, String requestBody) {
        Long id = loginInfo.getId();
        Class<T> entityClass = this.getEntityClass();
        T request = JSONUtil.toBean(requestBody, entityClass);
        AssertUtil.isTrue(id.equals(request.getId()), "暂无权限");
        T update = newInstance();
        update.setId(id);
        AssertUtil.isTrue(this.updateByDtoFillProps(loginInfo, request, update), "暂无权限");
        this.updateById(update);
    }

    /**
     * 开放更新的部分属性 如果为null默认不能更新
     */
    public Boolean updateByDtoFillProps(ILoginInfo loginInfo, T request, T update) {
        return false;
    }

    public void checkAndChangePassword(ILoginInfo loginInfo, String passwordOld, String password) {
        Long id = loginInfo.getId();
        this.checkOldPassword(id, passwordOld);
        T update = newInstance();
        update.setId(id);
        update.setPassword(PasswordUtils.encrypt_Password(password));
        super.updateById(loginInfo, update);
    }


    public void checkOldPassword(Long id, String passwordOldInput) {
        T entityOld = this.getById(id);
        String passwordOldDb = entityOld.getPassword();
        if (StrUtils.isNotBlank(passwordOldDb)) {
            AssertUtil.isTrue(passwordOldDb.equals(PasswordUtils.encrypt_Password(passwordOldInput)), "旧密码错误");
        }
    }

    public T register(String request, String ip, String lang, String smsCode) {
        throw new BusinessException(403, "暂无权限");
    }

    public void getActivity(HttpServletRequest request) {
    }
}
